# Install the required dependencies

# Declare working directory beforehand in an environment variable
# IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH = "path_to_your_folder"
# with the aid of usethis::edit_r_environ()
# Restart R session for the changes to take effect
path <- Sys.getenv("IMPERIAL_LEGAL_POLITICS_REPLICATION_PATH")
setwd(path)

# Read in the file with dependencies
packages <- readLines(con <- file("DEPENDENCIES", encoding = "UTF-8"))
packages <- gsub("^\\s+", "", packages[2:length(packages)])
packages <- gsub("\\s+.*$", "", packages)

# Install the uninstalled packages
missing_packages <- setdiff(packages, rownames(installed.packages()))

if ( length(missing_packages) > 0 ) {

	# Install the latest versions of all the packages
	install.packages(missing_packages, quiet = T) 

}

# Install stargazer with this fix: https://gist.github.com/alexeyknorre/b0780836f4cec04d41a863a683f91b53

## Quick fix for stargazer <= 5.2.3 is.na() issue with long model names in R >= 4.2
# Unload stargazer if loaded
detach("package:stargazer",unload=T)
# Delete it
remove.packages("stargazer")
# Download the source
download.file("https://cran.r-project.org/src/contrib/stargazer_5.2.3.tar.gz", destfile = "stargazer_5.2.3.tar.gz")
# Unpack
untar("stargazer_5.2.3.tar.gz")
# Read the sourcefile with .inside.bracket fun
stargazer_src <- readLines("stargazer/R/stargazer-internal.R")
# Move the length check 5 lines up so it precedes is.na(.)
stargazer_src[1990] <- stargazer_src[1995]
stargazer_src[1995] <- ""
# Save back
writeLines(stargazer_src, con="stargazer/R/stargazer-internal.R")
# Compile and install the patched package
install.packages("stargazer", repos = NULL, type="source")